package com.insightg3.android;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;

import com.google.api.translate.Language;

import android.app.Activity;
import android.content.Intent;
import android.net.ParseException;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.ContextMenu;
import android.view.MenuItem;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.View.OnClickListener;
import android.view.View.OnCreateContextMenuListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ListView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.TextView;

public class KakakuSearchResultActivity extends Activity {
	private ArrayList<SearchResultStatus> list = null;
	private SearchResultAdapter adapter = null;
	private String searchKey = "";
	private String orderBy = "pricerank";
    private static long startPrice = 0;
    private static long endPrice = 100000000;
    private static int searchNo = 1;
	
    private static long totalNum = 0l;
    
	@Override
	public void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);

		setContentView(R.layout.main_result_listview);

		ListView listview = (ListView) findViewById(R.id.lvResult);


		if(( savedInstanceState == null ) || ( savedInstanceState.isEmpty()) )
		{
		   // インテントから追加データを取り出い1�7
			searchKey = getIntent().getExtras().getString( "SEARCH_KEY" );
			if(getIntent().getExtras().getString("SEARCH_ORD") != null && getIntent().getExtras().getString("SEARCH_ORD").equals("Descend")) {
				orderBy = "-pricerank";
			} else {
				orderBy = "pricerank";
			}
			try {
				if(getIntent().getExtras().getString("SEARCH_NO") != null && !getIntent().getExtras().getString("SEARCH_NO").equals("")) {
					searchNo = Integer.parseInt(getIntent().getExtras().getString("SEARCH_NO"));
				}
				if(getIntent().getExtras().getString("SEARCH_MIN") != null && !getIntent().getExtras().getString("SEARCH_MIN").equals("")) {
					startPrice = Long.parseLong(getIntent().getExtras().getString("SEARCH_MIN"));
				} else {
					startPrice = 0;
				}
				if(getIntent().getExtras().getString("SEARCH_MAX") != null && !getIntent().getExtras().getString("SEARCH_MAX").equals("")) {
					endPrice = Long.parseLong(getIntent().getExtras().getString("SEARCH_MAX"));
				} else {
					endPrice = 100000000; 
				}
			} catch(NumberFormatException e) {
				startPrice = 0;
				endPrice = 100000000;
				searchNo = 1;
			}
		}
		
		((AndroidApplication)getApplication()).setSelectedItems(null);
		Log.d("Optional", searchKey + ", " + orderBy + ", " + searchNo + ", " + startPrice + ", " + endPrice);
		this.getSearchData(searchKey, orderBy, searchNo, startPrice, endPrice);

		Log.d("seard data is ok:", "start set date to adapter");

		
		//createDummyData();

		adapter = new SearchResultAdapter(this, R.layout.main_result_row, list);

		// // ListView hogeListView =
		// (ListView)this.findViewById(R.id.sr_list_view);

		// // hogeListView.setAdapter(adapter);
		
		//((AndroidApplication)getApplication()).setSelectedItems(list);
		
		listview.setAdapter(adapter);

		listview.setOnItemClickListener(new OnItemClickListener() {  
			@Override  
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,  
			long arg3) {  
				setTitle("Click"+arg2+" Item");  
			}  
			});  
		
		listview.setOnCreateContextMenuListener(new OnCreateContextMenuListener() {  

			@Override  
			public void onCreateContextMenu(ContextMenu menu, View v,ContextMenuInfo menuInfo) {  
			menu.setHeaderTitle("LongTouch-ContextMenu");     
			menu.add(0, 0, 0, "same key search in china ");  
			menu.add(0, 1, 0, "select to compare list");     
			menu.add(0, 2, 0, "to register keyword");
//			menu.add(0, 3, 0, "pre page");
//			menu.add(0, 4, 0, "next page");
			}  
			});   	
		// // setContentView(R.layout.main_result);

		// registerForContextMenu(listview);
		((Button) findViewById(R.id.PrevPage)).setOnClickListener(btnPrevListener);
		((Button) findViewById(R.id.NextPage)).setOnClickListener(btnNextListener); 
	}

	@Override  
	public boolean onContextItemSelected(MenuItem item) {  
		setTitle("Long touch "+item.getItemId()+" Item");   
		
		Intent intent = null;
		switch(item.getItemId()){
		case 0:
			//search in TaoBao
			String key = AndroidUtils.translateString(this.searchKey, Language.JAPANESE, Language.CHINESE_SIMPLIFIED);
	      intent = new Intent( KakakuSearchResultActivity.this, SearchResultActivity.class );

	       intent.putExtra( "SEARCH_KEY", key);
	       intent.putExtra( "SEARCH_NO", "1");
	       intent.putExtra("SEARCH_MIN", String.valueOf(startPrice));
			intent.putExtra("SEARCH_MAX", String.valueOf(endPrice));
			if(orderBy.equals("-pricerank")) {
				intent.putExtra("SEARCH_ORD", "Descend");
				Log.d("Optional", key + ", " + "price:desc" + ", 1, " + startPrice + ", " + endPrice);
			} else {
				intent.putExtra("SEARCH_ORD", "");
				Log.d("Optional", key + ", " + "price:asc" + ", 1, " + startPrice + ", " + endPrice);
			}
			
	       startActivity( intent );
	       break;
		case 1:
			ListView listview = (ListView) findViewById(R.id.lvResult);
			int size = listview.getChildCount();
			for (int i = 0; i < size; i++) {
				final View listDataView = listview.getChildAt(i);
				CheckBox chkSelect = (CheckBox) listDataView.findViewById(R.id.chkSelect);
				if (chkSelect.isChecked()) {
					((AndroidApplication)getApplication()).addSelectedItem(list.get(i));
					Log.d("selected item is:", list.get(i).toString() +";summay"+list.get(i).getSummary());
				}
			}
			List<SearchResultStatus> selectedItems = ((AndroidApplication)getApplication()).getSelectedItems();
			Log.d("selected items is :", selectedItems.toString());

	      intent = new Intent( KakakuSearchResultActivity.this, CompareResultActivity.class );
//
//	       intent.put( "COMPARE_RESULT", selectedItems);
	       startActivity( intent );

			break;
		case 2:
			intent = new Intent( KakakuSearchResultActivity.this, KeywordRegisterActivity.class );
			startActivity( intent );
			break;
		}

		return super.onContextItemSelected(item);  
	}  
	
	private String getSearchData(String key, String orderBy, int searchNo, long minPrice, long maxPrice) {

		String scheme = "http";

		String authority = "api.kakaku.com";

		String path = "/WebAPI/ItemSearch/Ver1.0/ItemSearch.aspx";

		String apiKey = "b0feed96f32dc8ee76e543d5d818ab3e";

		// String keyword = "�A�N�I�X";

		Uri.Builder uriBuilder = new Uri.Builder();

		uriBuilder.scheme(scheme);

		uriBuilder.authority(authority);

		uriBuilder.path(path);

		uriBuilder.appendQueryParameter("ApiKey", apiKey);
		uriBuilder.appendQueryParameter("Keyword", key);
		uriBuilder.appendQueryParameter("SortOrder", orderBy);
		uriBuilder.appendQueryParameter("HitNum", Integer.toString(10));
		uriBuilder.appendQueryParameter("PageNum", Integer.toString(searchNo));
		uriBuilder.appendQueryParameter("Charset", "utf8");
		uriBuilder.appendQueryParameter("MinPrice", Long.toString(minPrice));
		uriBuilder.appendQueryParameter("MaxPrice", Long.toString(maxPrice));

		String uri = uriBuilder.toString();

		HttpClient httpClient = new DefaultHttpClient();

		HttpParams params = httpClient.getParams();

		HttpConnectionParams.setConnectionTimeout(params, 10000);

		HttpConnectionParams.setSoTimeout(params, 20000);

		HttpUriRequest httpRequest = new HttpGet(uri);

		HttpResponse httpResponse = null;

		try {

			Log.d("httpRequest", httpRequest.getURI().toString());
			httpResponse = httpClient.execute(httpRequest);
			Log.d("OK", "request OK");
		}
		catch (ClientProtocolException e) {
			e.printStackTrace();
		}
		catch (IOException e) {
			e.printStackTrace();
		}

		String json = null;

		if (httpResponse != null
				&& httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {

			HttpEntity httpEntity = httpResponse.getEntity();

			try {
				
				this.createListViewData(httpResponse);
//				json = EntityUtils.toString(httpEntity);
			}
			catch (ParseException e) {
				e.printStackTrace();
			}
//			catch (IOException e) {
//			}
			finally {
				try {
					httpEntity.consumeContent();
				}
				catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		else {
			if (httpResponse == null) {
				Log.d("response data", "httpresponse is null");
			}

			else {
				Log.d("response status", "status:"
						+ httpResponse.getStatusLine().getStatusCode());
			}
		}
		httpClient.getConnectionManager().shutdown();
		return json;

	}

	private void createListViewData(HttpResponse httpResponse) {
		if(httpResponse == null) {
			TextView textview = (TextView) findViewById(R.id.txtResultTitle);
			textview.setText("Total Result is " + 0 + " items, this is page " + 0);
		}
		Log.d("createListViewData", "start create list data.");

		try {

			this.list = new ArrayList<SearchResultStatus>();

			SearchResultStatus item = new SearchResultStatus();

			// レスポンスをOutputStreamに書き出い1�7
			ByteArrayOutputStream ostream = new ByteArrayOutputStream();
			httpResponse.getEntity().writeTo(ostream);
			
			// XMLパーサーを生成すや1�7
			final XmlPullParserFactory factory = XmlPullParserFactory
					.newInstance();
			final XmlPullParser parser = factory.newPullParser();

			// XMLパーサに解析したい内容を設定する
			parser.setInput(new StringReader(ostream.toString()));
			boolean blnItemStart = false;

			// XML文章の終わりまでループして解析すや1�7
			for (int eventType = parser.getEventType(); eventType != XmlPullParser.END_DOCUMENT; eventType = parser
					.next()) {

				String tagName;
				String tagText;
				switch (eventType) {
				// TAGの始まり
				case XmlPullParser.START_TAG:
					// TAGの名前を取得する
					tagName = parser.getName();
					if (tagName.equals("NumOfResult")) {
						parser.next();
						if (parser.getEventType() == XmlPullParser.TEXT) {
							totalNum = Long.parseLong(parser.getText());

							TextView textview = (TextView) findViewById(R.id.txtResultTitle);
							textview.setText("Total Result is " + totalNum + " items, this is page " + searchNo);
						}
					}
						
					if (tagName.equals("Item")) {
						blnItemStart = true;
					}
					else
					// TAGの名前がProductName
					if (tagName.equals("ProductName")) {
						// 次の要素へ�1�7�む
						parser.next();
						// 要素がTEXTだったら内容を取り出い1�7
						if (parser.getEventType() == XmlPullParser.TEXT) {
							tagText = parser.getText();
							item.setSummary(tagText);
						}
					}
					else if (tagName.equals("MakerName")) {
						// 次の要素へ�1�7�む
						parser.next();
						// 要素がTEXTだったら内容を取り出い1�7
						if (parser.getEventType() == XmlPullParser.TEXT) {
							tagText = parser.getText();
							item.setTitle(tagText);
						}
					}
					else if (tagName.equals("ImageUrl")) {
						// 次の要素へ�1�7�む
						parser.next();
						// 要素がTEXTだったら内容を取り出い1�7
						if (parser.getEventType() == XmlPullParser.TEXT) {
							tagText = parser.getText();
							item.setImage(tagText);
						}
					}
					else if (tagName.equals("LowestPrice")) {
						// 次の要素へ�1�7�む
						parser.next();
						// 要素がTEXTだったら内容を取り出い1�7
						if (parser.getEventType() == XmlPullParser.TEXT) {
							tagText = parser.getText();
							item.setPrice(tagText);
						}
					}
					break;
				// TAGのおわり
				case XmlPullParser.END_TAG:
					// TAGの名前を取得する
					tagName = parser.getName();
					if (tagName.equals("Item") && blnItemStart) {
						this.list.add(item);
						item = new SearchResultStatus();
						blnItemStart = false;
					}
					break;
				}
			}
			Log.d("paser xml data", list.toString());
		}
		catch (ClientProtocolException e) {
			e.printStackTrace();
		}
		catch (IOException e) {
			e.printStackTrace();
		} catch (XmlPullParserException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
		OnClickListener btnPrevListener = new OnClickListener() {
		public void onClick(View v) {
			if(searchNo > 1) {
				TextView textview = (TextView) findViewById(R.id.txtResultTitle);
				searchNo--;
				if(searchKey != null && !searchKey.equals("")) {
					getSearchData(searchKey, orderBy, searchNo, startPrice, endPrice);
					textview.setText("Total Result is " + totalNum + " items, this is page " + searchNo);
				}
				ListView listview = (ListView) findViewById(R.id.lvResult);
				adapter = new SearchResultAdapter(KakakuSearchResultActivity.this, R.layout.main_result_row, list);
				listview.setAdapter(adapter);
			}
		}
	};

	OnClickListener btnNextListener = new OnClickListener() {
		public void onClick(View v) {
			if(searchNo * 10 < totalNum && searchNo < 100) {
				TextView textview = (TextView) findViewById(R.id.txtResultTitle);
				searchNo++;
				if(searchKey != null && !searchKey.equals("")) {
					getSearchData(searchKey, orderBy, searchNo, startPrice, endPrice);
					textview.setText("Total Result is " + totalNum + " items, this is page " + searchNo);
				}
				ListView listview = (ListView) findViewById(R.id.lvResult);
				adapter = new SearchResultAdapter(KakakuSearchResultActivity.this, R.layout.main_result_row, list);
				listview.setAdapter(adapter);
			}
		}
	};
	
}
